﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Jemgine.Hex
{
    /// <summary>
    /// An off-set origin rectangular array. Valid X indicies are from OriginX to OriginX + Width exclusive.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class Grid<T> where T : class, new()
    {
        public int Width { get; private set; }
        public int Height { get; private set; }
        public int OriginX { get; private set; }
        public int OriginY { get; private set; }
        private T[,] Data;

        public T this[Coordinate Coord] { get { return this.GetAt(Coord); } }
        public T this[int X, int Y] { get { return this.GetAt(new Coordinate(X, Y)); } }

        public Grid(int Width, int Height)
        {
            Initialize(Width, Height, 0, 0);
        }

        private void Initialize(int Width, int Height, int OriginX, int OriginY)
        {
            this.Width = Width;
            this.Height = Height;
            Data = new T[Width, Height];
            this.OriginX = OriginX;
            this.OriginY = OriginY;

            for (int X = 0; X < Width; ++X)
                for (int Y = 0; Y < Height; ++Y)
                    Data[X, Y] = new T();
        }

        public Grid(int Width, int Height, int OriginX, int OriginY)
        {
            Initialize(Width, Height, OriginX, OriginY);
        }

        public T GetAt(Coordinate Coord)
        {
            Coord.X -= OriginX;
            Coord.Y -= OriginY;
            if (Coord.X < 0 || Coord.X >= Width) return null;
            if (Coord.Y < 0 || Coord.Y >= Height) return null;
            return Data[Coord.X, Coord.Y];
        }

        public bool InBounds(Coordinate Coord)
        {
            Coord.X -= OriginX;
            Coord.Y -= OriginY;
            if (Coord.X < 0 || Coord.X >= Width) return false;
            if (Coord.Y < 0 || Coord.Y >= Height) return false;
            return true;
        }
    }
}
